package com.lnold.redis.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class ConfigSubscriber implements MessageListener {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private ConfigUpdateListener configUpdateListener;

    public void subscribe() {
        redisTemplate.getConnectionFactory().getConnection().subscribe(this, "configUpdates".getBytes());
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String config = (String) redisTemplate.getValueSerializer().deserialize(message.getBody());
        configUpdateListener.handleConfigUpdate(config);
    }
}
